<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <div style="margin-bottom: 20px;display: flex;justify-content: space-between">
      <a-button @click="saveAll">全部保存</a-button>
      <a-button @click="generateAllocate">生成调拨单</a-button>
    </div>
    <a-table
      ref="table"
      size="small"
      bordered
      rowKey="id"
      class="j-table-force-nowrap"
      :scroll="{ x: true }"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :customRow="clickThenSelect"
      @change="handleTableChange"
    >
      <template slot-scope="text, record" slot="number">
        <a-input-number v-model:value="record.number" v-if="record.selectable"></a-input-number>
        <span v-else>{{ text }}</span>
      </template>
      <template slot="outputWarehouse" slot-scope="text, record">
        <j-dict-select-tag
          v-model:value="record.outputWarehouse"
          v-if="false"
          dict-code="hf_warehouse,warehouse_name,id"
          @change="changOutputWarehouse($event, record)"
          style="width: 100%;"
        ></j-dict-select-tag>
        <span v-else>{{ text }}</span>
      </template>
      <template slot="inputWarehouse" slot-scope="text, record">
        <j-dict-select-tag
          v-model:value="record.inputWarehouse"
          v-if="record.selectable"
          dict-code="hf_warehouse,warehouse_name,id"
          @change="changInputWarehouse($event, record)"
          style="width: 100px;"
        ></j-dict-select-tag>
        <span v-else>{{ text }}</span>
      </template>
      <template slot="action" slot-scope="text, record">
        <div class="" v-show="record.status !== 1">
          <span v-if="record.editable">
            <a @click="() => save(record)">保存</a>
            <a-divider type="vertical" style="background-color: grey"></a-divider>
            <a @click="() => cancel(record)">取消</a>
          </span>
          <span v-else>
            <a @click="edit(record)">编辑</a>
          </span>
        </div>
      </template>
    </a-table>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@api/manage'
import { ajaxGetDictItems } from '@api/api'

export default {
  name: 'GenerateProductAllocate',
  props: {
    mainId: {
      type: String,
      default: '',
      required: false
    }
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['sourceId'] = val
        }
      }
    }
  },
  data() {
    return {
      title: '生成产品调拨单',
      width: 1500,
      visible: false,
      confirmLoading: false,
      model: [],
      editingKey: '',
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '30', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '调出仓库',
          align: 'center',
          dataIndex: 'warehouse_dictText',
          scopedSlots: { customRender: 'outputWarehouse' }
        },
        {
          title: '调入仓库',
          align: 'center',
          dataIndex: 'inputWarehouse_dictText',
          scopedSlots: { customRender: 'inputWarehouse' }
        },
        {
          title: '生产数量',
          align: 'center',
          dataIndex: 'actualInputNumber',
          scopedSlots: { customRender: 'actualInputNumber' }
        },
        {
          title: '调拨数量',
          align: 'center',
          dataIndex: 'number',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        generateAllocate: '/warehouse/hfAllocate/generateProductAllocate',
        list: '/production/hfProductionProductInput/listHInputDetailByMainId'
      }
    }
  },
  methods: {
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            // this.onSelectChange(record.id.split(','), [record])
          }
        }
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    handleOk() {
      this.confirmLoading = true
    },
    loadData1(id) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      let params = this.queryParam
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach(item => {
              item.selectable = true
              item.editable = true
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    changInputWarehouse(warehouse, record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.id === record.id)
      let dictOptions
      ajaxGetDictItems('hf_warehouse,warehouse_name,id', null).then(res => {
        if (res.success) {
          dictOptions = res.result
          target.inputWarehouse_dictText = dictOptions.find(item => item.value === record.inputWarehouse).text
          target.inputWarehouse = warehouse
          this.dataSource = newData
        }
      })
    },
    changOutputWarehouse(warehouse, record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      let dictOptions
      ajaxGetDictItems('hf_warehouse,warehouse_name,id', null).then(res => {
        if (res.success) {
          dictOptions = res.result
          target.outputWarehouse_dictText = dictOptions.find(item => item.value === record.outputWarehouse).text
          target.outputWarehouse = warehouse
          this.dataSource = newData
        }
      })
    },
    saveAll() {
      const newData = [...this.dataSource]
      newData.forEach(item => {
        if (item.number === null || item.number === undefined) {
          this.$message.error('请输入数量')
          return
        }
        if (item.number > item.actualInputNumber) {
          this.$message.error('调拨数量不能大于生产数量')
          return
        }
        if (!item.inputWarehouse) {
          this.$message.error('请选择仓库')
          return
        }
        item.selectable = false
        item.editable = false
      })
      this.dataSource = newData
    },
    generateAllocate() {
      let body = this.dataSource
      body.forEach(item => {
        item.outputWarehouse = item.warehouse
      })
      postAction(`${this.url.generateAllocate}/${this.mainId}`, body).then(res => {
        if (res.success) {
          this.$message.success('调拨成功')
          this.close()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    save(record) {
      if (record.number === null || record.number === undefined) {
        this.$message.error('请输入数量')
        return
      }
      if (record.number > record.actualInputNumber) {
        this.$message.error('调拨数量不能大于生产数量')
        return
      }
      if (!record.inputWarehouse) {
        this.$message.error('请选择仓库')
      }
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.id === record.id)
      if (target) {
        target.editable = false
        target.selectable = false
        this.dataSource = newData
      }
    },
    cancel(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.id === record.id)
      if (target) {
        target.editable = false
        target.selectable = false
        this.dataSource = newData
      }
      this.selectValue = ''
    },
    edit(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.id === record.id)
      if (target) {
        target.editable = true
        target.selectable = true
        this.selectValue = target.materialCode
        this.dataSource = newData
      }
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData1()
    }
  }
}
</script>

<style scoped></style>
